package com.sunny.tree.action;

import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import com.sunny.tree.model.Tree;
import com.sunny.tree.service.TreeService;
import org.apache.struts2.ServletActionContext;
import org.codehaus.jackson.map.ObjectMapper;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Created by tongchengke on 2016/8/17.
 */

@Controller
@Scope("prototype")
public class TreeAction extends ActionSupport implements ModelDriven<Tree>{

    @Resource
    private TreeService treeService;

    /**
     * 跳转tree页面
     * @return
     */
    public String toTreeView(){

        return SUCCESS;
    }

    public void getTreeByPid() throws IOException {

        ObjectMapper objectMapper = new ObjectMapper();
        String json = objectMapper.writeValueAsString(treeService.selectTreeByPid(tree));

        HttpServletResponse response = ServletActionContext.getResponse();
        response.setContentType("text/html;charset=UTF-8");
        response.getWriter().write(json);
        response.getWriter().flush();
        response.getWriter().close();

    }


    private Tree tree;

    public Tree getTree() {
        return tree;
    }

    public void setTree(Tree tree) {
        this.tree = tree;
    }

    @Override
    public Tree getModel() {
        if(tree==null){
            tree = new Tree();
        }
        return tree;
    }
}
